package com.yuan.controller;

import com.yuan.bean.LibraryCard;
import com.yuan.bean.UserLogin;
import com.yuan.service.LibraryCardService;
import com.yuan.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LibraryCardController {

    @Autowired
    LibraryCardService libraryCardService;

    @Autowired
    UserLoginService userLoginService;

    /**
     * 返回对应的还书页面
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/libraryCard")
    public String libraryCard(HttpSession session,Model model){
        return "libraryCard";
    }


    @GetMapping("/demo")
    public String demo(){
        return "demo";
    }

    /**
     * 借书操作
     * @param bookId  获取当前服务器中保存的用户对象的用户id
     * @param session
     */
    @ResponseBody
    @GetMapping("/borrow")
    public boolean borrowBook(@RequestParam("bookId")Integer bookId, HttpSession session){
        final UserLogin user =(UserLogin) session.getAttribute("User");
        Integer userId=user.getUserId();
        final boolean b = libraryCardService.borrowBook(userId, bookId);
        return b;
    }

    /**
     * 还书操作
     * @param bookNo  获取书名
     * @param session   获取当前操作对象的id
     * @return
     */
    @ResponseBody
    @GetMapping("/returnBook")
    public boolean returnBook(@RequestParam("bookNo")Integer bookNo,HttpSession session){
        UserLogin user=(UserLogin)session.getAttribute("User");
        Integer userId=user.getUserId();
        final boolean b = libraryCardService.returnBook(userId, bookNo);
        return b;
    }


    /**
     * 查询当前用户的借书情况
     * @param session
     * @return
     */
    @ResponseBody
    @GetMapping("/lc")
    public List<LibraryCard> libraryCards(HttpSession session){
        final UserLogin user =(UserLogin) session.getAttribute("User");
        Integer userId=user.getUserId();
        final List<LibraryCard> libraryCards = libraryCardService.selectAllByUserId(userId);
        return libraryCards;
    }

    //获取用户的剩余借书数量
    @ResponseBody
    @GetMapping("/selectNum")
    public int selectNum(HttpSession session){
        UserLogin user=(UserLogin) session.getAttribute("User");
        Integer userId=user.getUserId();
        final int i = userLoginService.selectNum(userId);
        return i;
    }

}
